package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @date 2025/9/28
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/showUpload")
    public String showUpload(){
        return "upload";
    }
    @RequestMapping("/upload")
    public void puload(String username , @RequestParam(value = "file" , required = false)CommonsMultipartFile file , HttpSession session){
        System.out.println("username:"+username);
        System.out.println("文件是否为空:"+file.isEmpty());
        if(!file.isEmpty()){
            String path = session.getServletContext().getRealPath("/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date()));
            System.out.println("path:"+path);
            File f = new File(path);
            f.mkdirs();
            try {
                file.transferTo(new File(path , file.getOriginalFilename()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @RequestMapping("/showDowenload")
    public String showDowenload(){
        return "download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        //指定需要下载的文件资源
        String path = session.getServletContext().getRealPath("/js/jquery-3.4.3.min.js");
        File file = new File(path);
        //设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        ContentDisposition disposition = ContentDisposition.builder("addchment").filename("jquery-3.4.3.min.js").build();
        headers.setContentDisposition(disposition);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file) , headers , HttpStatus.CREATED);
    }
}
